/*
    jME Terra package. A Terrain Engine for the Java Monkey Engine.
    Copyright (C) 2005-2006,  Tijl Houtbeckers
    
    **** LICENSE: ****

	This library is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public
	License as published by the Free Software Foundation,
	version 2.1.
	
	This library is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
	Lesser General Public License for more details.
	
	You should have received a copy of the GNU Lesser General Public
	License along with this library; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

	**** CONTACT: ****

    I can be reached through the jmonkeyengine.com forums (user "llama"), 
    or the jmonkeyengine.com contact page:
    jmonkeyengine.com/index.php?option=com_contact&task=view&contact_id=5           

*/

/**
 * @author Tijl Houtbeckers
 */

package org.llama.jmex.terra.format;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.zip.Deflater;

import org.llama.jmex.terra.HeightMapManager;
import org.llama.jmex.terra.util.TerraBuilder;

public class AscTerraBuilder extends TerraBuilder {

	public AscTerraBuilder(String[] a) {
		build(a);
	}

	public static void main(String a[]) {
		new AscTerraBuilder(a);
	}
	
	public void build(String filename, String pre_in, String pre_out, int blocksize, int mapmulti) throws IOException {
		System.out.println("Opening: "+pre_in+filename+".asc");
		FileInputStream fis = new FileInputStream(pre_in+filename+".asc");
		InputStreamReader inr = new InputStreamReader(fis);
		
		StringBuffer headers = new StringBuffer();
		int rcount = 0;
		while (rcount < 6) {
			char c = (char) inr.read();
			if (c == '\r')
				rcount++;
			headers.append(c);
		}
		
		BufferedReader bufr = new BufferedReader(new StringReader(headers.toString()));
		
		int ncols = Integer.parseInt(bufr.readLine().substring(6).trim());
		System.out.println("ncols: "+ncols);
		int nrows = Integer.parseInt(bufr.readLine().substring(6).trim());
		System.out.println("nrows: "+nrows);
		bufr.readLine();
		bufr.readLine();
		bufr.readLine();
		float nodata = Float.parseFloat(bufr.readLine().substring(13).trim());
		System.out.println("no_data: "+nodata);
		
		
		StreamTokenizer st = new StreamTokenizer(inr);
		st.eolIsSignificant(false);
		
		final int mapsize = blocksize * mapmulti;
		
		float[][] grid = new float[mapsize][ncols];
		
		HeightMapManager hm = new HeightMapManager(mapsize);
        FileMapStore store = (new FileMapStore(pre_out+filename,true));
        ZLibMapCompressor comp = new ZLibMapCompressor(Deflater.BEST_COMPRESSION,Deflater.DEFAULT_STRATEGY);
        
		
		for (int y = 0; y < (nrows/mapsize); y+=1) {
			for (int i = 0; i < mapsize; i++) { 
				if ( i % 100 == 0)
					System.out.println("line: "+(y*mapsize+i));
				for (int x = 0; x < ncols; x++) {
					st.nextToken();
					float heigth = (float)st.nval;
					if (heigth == nodata)
						heigth = 0;
					else {
						heigth*=10;
						heigth+=20;
					}
					grid[i][x] = heigth;
				}
			}
			
			for (int i = 0; i < ncols/mapsize; i++) {
				int xx = i - ((ncols / mapsize) / 2);
				int yy = y - ((ncols / mapsize) / 2);
				
				System.out.println("make map: "+xx+" "+yy);					
				
                ByteBuffer buf = ByteBuffer.allocate(mapsize * mapsize * 4);
                buf.rewind();
                IntBuffer intbuf = buf.asIntBuffer();
                for (int yyy = 0; yyy < mapsize; yyy++) {
                	for (int xxx = 0; xxx < mapsize; xxx++) {
                		intbuf.put(yyy*mapsize+xxx, (int)grid[yyy][xxx+(i*mapsize)]);
                	}
                }
                hm.addMap(xx, yy, buf);
                hm.saveCompressedMapToStore(xx, yy, store, true, false, false, false, null, comp );
                System.out.println("mapfile saved: "+xx+":"+yy);
			}
		}
	}

}
